/**
 * 调整十六进制颜色的亮度 (RGB 方法)
 * @param {string} hex - 十六进制颜色字符串，如 "#ff4500"
 * @param {number} percent - 亮度调整百分比，-100 到 100 之间。正数变亮，负数变暗。
 * @returns {string} 调整后的十六进制颜色字符串
 */
function adjustBrightnessRGB(hex, percent) {
	// 移除 # 号
	hex = hex.replace(/^#/, '');
	// 解析 R, G, B 分量
	let r = parseInt(hex.substring(0, 2), 16);
	let g = parseInt(hex.substring(2, 4), 16);
	let b = parseInt(hex.substring(4, 6), 16);

	// 计算调整值
	let adjust = Math.round(255 * (percent / 100));

	// 调整每个分量，并确保在 0-255 范围内
	let newR = Math.max(0, Math.min(255, r + adjust));
	let newG = Math.max(0, Math.min(255, g + adjust));
	let newB = Math.max(0, Math.min(255, b + adjust));

	// 将分量转换回十六进制，并补零
	let toHex = (c) => ('0' + c.toString(16)).slice(-2);
	return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`.toUpperCase();
}

// 判断颜色是否为深色
function isDarkColor(hex) {
	if (!/^#[0-9A-F]{6}$/i.test(hex)) {
		throw new Error('Invalid HEX color format');
	} else {
		let threshold = 128;
		let bigint = parseInt(hex.slice(1), 16);
		let r = (bigint >> 16) & 255;
		let g = (bigint >> 8) & 255;
		let b = bigint & 255;
		let brightness = 0.299 * r + 0.587 * g + 0.114 * b;
		return brightness < threshold;
	}
}

function setHoverColor(color, percent) {
	let isDark = isDarkColor(color);
	let hoverColor = adjustBrightnessRGB(color, percent);
	document.documentElement.style.setProperty('--hover-color', hoverColor);
	document.documentElement.style.setProperty('--header-color', !isDark ? '#303133' : '#fff');
}

export default setHoverColor;